package com.accompany.fragment.my.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.accompany.R;
import com.accompany.api.bean.UploadNichengMsgBean;
import com.accompany.api.category.UploadNichengMsgCategory;
import com.accompany.api.presenter.UploadNichengMsgPresenter;
import com.accompany.base.BaseActivity;
import com.accompany.dialog.OnUploadPicDialogClickListener;
import com.accompany.dialog.UploadPicDialog;
import com.accompany.main.ConstantStaticUrl;
import com.accompany.utils.CameraUtils;
import com.accompany.utils.FullScreenUtils;
import com.accompany.utils.IDCardValidateUtils;
import com.accompany.utils.SPUtils;
import com.accompany.utils.ToastUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 信息说明:
 * company: 兰州丰荣信息科技有限公司
 * 创建时间: on 2022/5/12 14 ：33
 * 项目名称：yuanban
 */
public class UserPersonalActivity extends BaseActivity implements UploadNichengMsgCategory.View {
    @BindView(R.id.base_title)
    TextView mTitleMsg;
    @BindView(R.id.icon_personal)
    CircleImageView mIconImage;
    @BindView(R.id.nick_name)
    TextView mEditText;
    @BindView(R.id.edit_sfz)
    TextView mEditSfz;
    @BindView(R.id.edit_mobile_person)
    TextView mMobilePhone;
    private UploadPicDialog dialog;
    private UploadNichengMsgPresenter mPresenter;
    private long mUserId;
    private String mIconPath, sfzhm, mNichengName, mToken;
    @Override
    public int getLayoutId() {
        return R.layout.activity_person_view;
    }
    @Override
    public void initLayoutView() {
        FullScreenUtils.getInstance().fullScreen(UserPersonalActivity.this, true);
        mTitleMsg.setText("个人信息");
        mPresenter = new UploadNichengMsgPresenter(this);
        SetPersenter(mPresenter);
        String mIconImageAvartar = getIntent().getStringExtra("iconImage");
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.error(R.drawable.logo_circler_bg)
                .circleCrop()
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE);
        Glide.with(UserPersonalActivity.this)
                .load(mIconImageAvartar)
                .apply(requestOptions)
                .into(mIconImage);
        String mNickName = getIntent().getStringExtra("nickName");
        String mSfzCardId = getIntent().getStringExtra("mSfzCardId");
        mEditSfz.setText(mSfzCardId);
        mEditText.setText(mNickName);
        mMobilePhone.setText(getIntent().getStringExtra("mobile"));
        mToken = (String) SPUtils.get(UserPersonalActivity.this, ConstantStaticUrl.mToken, "");
        SharedPreferences sharedPreferences = UserPersonalActivity.this.getSharedPreferences("First", MODE_PRIVATE);
        mUserId = sharedPreferences.getLong(ConstantStaticUrl.userId, 0);
    }
    @OnClick({R.id.base_back, R.id.relat_icon})  //, R.id.submit_person
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.base_back:
                finishWitchAnimation();
                break;
//            case R.id.relat_icon:
//                selectIconImageDialog();
//                break;
//            case R.id.submit_person:
//                sfzhm = mEditSfz.getText().toString().trim();
//                mNichengName = mEditText.getText().toString().trim();
//                if (sfzhm.equals("")) {
//                    ToastUtil.showToastINFO(UserPersonalActivity.this, "请输入就诊人身份证号码");
//                    return;
//                } else {
//                    try {
//                        if (!IDCardValidateUtils.checkIdCardNum(sfzhm)) {
//                            ToastUtil.showToastINFO(UserPersonalActivity.this, "身份证号码输入有误");
//                            mEditSfz.setText("");
//                            return;
//                        } else {
//                            JSONObject result = new JSONObject();
//                            try {
//                                result.put("acdId", String.valueOf(mUserId));
//                                result.put("acdName", mNichengName);
//                                result.put("certificateType", sfzhm);
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//                            mPresenter.uploadImageNicheng(mToken, result.toString());
//                        }
//                    } catch (ParseException e) {
//                        e.printStackTrace();
//                    }
//                }
//                break;
        }
    }
    /**
     * 拍照弹出窗口
     */
    private void selectIconImageDialog() {
        dialog = new UploadPicDialog(this, new OnUploadPicDialogClickListener() {
            // TODO: 2022/5/3 拍照
            @Override
            public void onPhoto(Dialog dialog) {
                // 权限申请
                if (ContextCompat.checkSelfPermission(UserPersonalActivity.this,
                        Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                        || ContextCompat.checkSelfPermission(UserPersonalActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    // 权限还没有授予，需要在这里写申请权限的代码
                    ActivityCompat.requestPermissions(UserPersonalActivity.this,
                            new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 300);
                } else {
                    Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    Uri imageUri = CameraUtils.getOutputMediaFileUri(UserPersonalActivity.this);
                    openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    //Android7.0添加临时权限标记，此步千万别忘了
                    openCameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    startActivityForResult(openCameraIntent, 100);
                }

                dialog.dismiss();
            }

            // TODO: 2022/5/3 从相册选择图片
            @Override
            public Intent onPicture(Dialog dialog) {
                // 权限申请
                if (ContextCompat.checkSelfPermission(UserPersonalActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //权限还没有授予，需要在这里写申请权限的代码
                    ActivityCompat.requestPermissions(UserPersonalActivity.this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200);
                } else {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, 200);
                }
                dialog.dismiss();
                return null;
            }

            @Override
            public void onCancel(Dialog dialog) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            Bitmap originBitmap = CameraUtils.getBitmapWithRightRotation(CameraUtils.sCameraPath);
            mIconImage.setImageBitmap(originBitmap);
            mIconPath = CameraUtils.sCameraPath;
            mPresenter.uploadImage(mUserId, mToken, mIconPath);
        } else if (requestCode == 200) {
            mIconPath = CameraUtils.getRealPathFromUri(UserPersonalActivity.this, data.getData());
            Bitmap originBitmap = CameraUtils.getBitmapWithRightRotation(mIconPath);
            mIconImage.setImageBitmap(originBitmap);
            mPresenter.uploadImage(mUserId, mToken, mIconPath);
        }
    }

    @Override
    public void uploadImage(UploadNichengMsgBean bean) {
        if (bean.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            ToastUtil.showToastSUCCESS(UserPersonalActivity.this, "头像上传成功");
        } else {
            ToastUtil.showToastINFO(UserPersonalActivity.this, bean.getMsg());
        }
    }

    @Override
    public void uploadImageNicheng(UploadNichengMsgBean bean) {
        if (bean.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            ToastUtil.showToastSUCCESS(UserPersonalActivity.this, "个人信息更新成功");
            Intent intent = new Intent();
            //把返回数据存入Intent
            intent.putExtra("nickName", bean.getData().getNickName());
            intent.putExtra("iconImage", bean.getData().getAvatar());
//            mEditText.setHint("");
            //设置返回数据
            UserPersonalActivity.this.setResult(200, intent);//RESULT_OK为自定义常量
            //关闭Activity
            UserPersonalActivity.this.finish();
        } else {
            ToastUtil.showToastINFO(UserPersonalActivity.this, bean.getMsg());
        }
    }

    @Override
    public void SetPersenter(Object persenter) {
    }

    @Override
    public void OnShowErrorMsg(String mErrorMsg) {
        ToastUtil.showToastERROR(UserPersonalActivity.this, mErrorMsg);
    }

}
